package com.xykj.enterprise.wechat.event.service;

import com.alibaba.fastjson.JSONArray;
import com.xykj.enterprise.wechat.bean.ext.identity.AccessToken;
import com.xykj.enterprise.wechat.bean.ext.identity.Auth_corp_info;
import com.xykj.enterprise.wechat.bean.ext.identity.GetPermanentCodeVo;
import com.xykj.enterprise.wechat.bean.ext.identity.SuiteAccessToken;
import com.xykj.enterprise.wechat.core.dao.CorpExtDao;
import com.xykj.enterprise.wechat.core.dao.SuiteTicketDao;
import com.xykj.enterprise.wechat.core.dao.corp.AuthCorpDao;
import com.xykj.enterprise.wechat.core.model.dodb.AuthCorp;
import com.xykj.enterprise.wechat.core.model.dodb.CorpExt;
import com.xykj.enterprise.wechat.event.config.ExtClient;
import com.xykj.enterprise.wechat.event.service.ext.AccessTokenUtil;
import com.xykj.enterprise.wechat.event.service.ext.SuiteAccessTokenUtil;
import com.xykj.enterprise.wechat.util.biz.BizUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author zhouxu
 * @create 2021-03-31 14:54
 */
@Service
@Slf4j
public class CorpServiceImpl implements CorpService {

    @Autowired
    private AuthCorpDao authCorpDao;
    @Autowired
    private CorpExtDao corpExtDao;
    @Autowired
    private SuiteTicketDao suiteTicketDao;
    @Autowired
    private ExtClient extClient;

    @Override
    public void save(GetPermanentCodeVo getPermanentCodeVo) {
        Auth_corp_info auth_corp_info = getPermanentCodeVo.getAuth_corp_info();
        if (auth_corp_info == null) {
            BizUtil.exception("永久授权数据异常，auth_corp_info 为空");
        }

        if (authCorpDao.getByCorpid(auth_corp_info.getCorpid()) == null) {
            authCorpDao.save(
                    auth_corp_info.getCorpid(),
                    getPermanentCodeVo.getAccess_token(),
                    getPermanentCodeVo.getExpires_in(),
                    getPermanentCodeVo.getPermanent_code(),
                    JSONArray.toJSON(auth_corp_info).toString(),
                    getPermanentCodeVo.getAuth_info() == null ? null : JSONArray.toJSON(getPermanentCodeVo.getAuth_info()).toString(),
                    getPermanentCodeVo.getAuth_user_info() == null ? null : JSONArray.toJSON(getPermanentCodeVo.getAuth_user_info()).toString(),
                    getPermanentCodeVo.getDealer_corp_info() == null ? null : JSONArray.toJSON(getPermanentCodeVo.getDealer_corp_info()).toString(),
                    getPermanentCodeVo.getRegister_code_info() == null ? null : JSONArray.toJSON(getPermanentCodeVo.getAuth_user_info()).toString()

            );
        } else {
            authCorpDao.update(
                    auth_corp_info.getCorpid(),
                    getPermanentCodeVo.getAccess_token(),
                    getPermanentCodeVo.getExpires_in(),
                    getPermanentCodeVo.getPermanent_code(),
                    JSONArray.toJSON(auth_corp_info).toString(),
                    getPermanentCodeVo.getAuth_info() == null ? null : JSONArray.toJSON(getPermanentCodeVo.getAuth_info()).toString(),
                    getPermanentCodeVo.getAuth_user_info() == null ? null : JSONArray.toJSON(getPermanentCodeVo.getAuth_user_info()).toString(),
                    getPermanentCodeVo.getDealer_corp_info() == null ? null : JSONArray.toJSON(getPermanentCodeVo.getDealer_corp_info()).toString(),
                    getPermanentCodeVo.getRegister_code_info() == null ? null : JSONArray.toJSON(getPermanentCodeVo.getAuth_user_info()).toString()

            );
        }


    }

    @Override
    public void initExtInfo(String corpid) {
        CorpExt ext = corpExtDao.get(corpid);
        if (ext == null) {
            corpExtDao.save(corpid);
        }

    }

    @Override
    public AuthCorp getByCorpid(String corpid, String suiteId, String secret) {
        AuthCorp authCorp = authCorpDao.getByCorpid(corpid);

        // 校验 token 是否失效
        if (authCorp.isExpired()) {
            authCorp = refreshAccessToken(corpid, suiteId, secret);
        }
        if (authCorp == null){
            BizUtil.exception("access_token 异常");
        }
        return authCorp;
    }

    @Override
    public AuthCorp refreshAccessToken(String corpid, String suiteId, String secret) {
        AuthCorp authCorp = authCorpDao.getByCorpid(corpid);
        // 获取 suite_access_token
        SuiteAccessToken suiteAccessToken = SuiteAccessTokenUtil.get(
                extClient,
                suiteId,
                secret,
                suiteTicketDao.getLatest(suiteId).getSuitTicket()
        );
        log.debug("*******************suiteAccess_token:{}", suiteAccessToken.toString());

        // 重新获取 access_token
        AccessToken accessToken = AccessTokenUtil.get(
                extClient,
                suiteAccessToken.getSuite_access_token(),
                corpid,
                authCorp.getPermanentCode()
        );
        log.debug("*******************access_token:{}", accessToken.toString());
        // 更新到数据库
        return authCorpDao.resetAccessToken(corpid, accessToken.getAccess_token(), accessToken.getExpires_in());
    }

}
